//
//  PError.m
//  iPiano
//
//  Created by wuxinting on 16/1/18.
//  Copyright © 2016年 wuxinting. All rights reserved.
//

#import "PError.h"
#import "XSafeGrammar.h"

static NSMutableDictionary<NSNumber *, NSString *> * codeMsgMap;
static NSString * const ErrorDefaultMsg = @"发生了一个错误";
@interface PError ()

@property (nonatomic) NSInteger code;
@property (nonatomic, copy) NSString * msg;

@end

@implementation PError

- (instancetype)init {
    if (self = [super init]) {
        codeMsgMap = [NSMutableDictionary dictionary];
#define ERRMAP(_msg_, _code_) \
        [codeMsgMap setObject:_msg_ forKey:[NSNumber numberWithInteger:_code_]];
        ERRMAP(@"查无此项", ErrorDoesNotExist);
        ERRMAP(@"密码错误", ErrorLoginPasswordIncorrect);
        ERRMAP(@"用户名或密码格式错误", ErrorLoginUserNameOrPasswordIllegal);
        ERRMAP(@"用户已存在", ErrorLoginUserExist);
    }
    return self;
}

+ (PError *)errorWithError:(NSError *)error {
    PError * pError = [[PError alloc] init];
    pError.error = error;
    pError.code = error.code;
    pError.msg = [codeMsgMap objectForKey:[NSNumber numberWithInteger:pError.code]];
    if (!XStringCheck(pError.msg)) {
        pError.msg = [error.userInfo objectForKey:NSLocalizedDescriptionKey];
        if (!XStringCheck(pError.msg)) {
            pError.msg = ErrorDefaultMsg;
        }
    }
    return pError;
}

+ (PError *)errorWithResponse:(NSHTTPURLResponse *)res {
    PError * pError = [[PError alloc] init];
    pError.code = res.statusCode;
    pError.msg = [codeMsgMap objectForKey:[NSNumber numberWithInteger:pError.code]];
    if (!XStringCheck(pError.msg)) {
        pError.msg = ErrorDefaultMsg;
    }
    return pError;
}

+ (PError *)errorWithCode:(NSInteger)code andMsg:(NSString *)msg {
    PError * pError = [[PError alloc] init];
    pError.code = code;
    pError.msg = msg;
    return pError;
}

#pragma mark - Getters
- (BOOL)isSuccess {
    return self.code == D_ERR_CODE_SUCCESS;
}

@end

@implementation NSError (PError)

- (NSString *)message {
    return [self.userInfo objectForKey:NSLocalizedDescriptionKey];
}

@end

NSInteger const ErrorInterval = 50;
NSInteger const ErrorBase = 600;
NSInteger const ErrorDoesNotExist = ErrorBase + 1;

NSInteger const ErrorLoginBase = ErrorBase + 10;
NSInteger const ErrorLoginPasswordIncorrect = ErrorLoginBase + 1;
NSInteger const ErrorLoginUserNameOrPasswordIllegal = ErrorLoginBase + 2;
NSInteger const ErrorLoginUserExist = ErrorLoginBase + 3;
NSInteger const ErrorLoginEnd = ErrorLoginBase + ErrorInterval;
